const { sequelize } = require('../../core/db')
const {Sequelize, Model, Op} = require('sequelize')
const {Art} = require('./art')

class Favor extends Model {
  // 业务表
  // 点赞
  static async like(art_id, type, uid ) {
    // 添加记录  classic fav_nums 数据库事务--保持数据的一致性  ACID原子性 一致性 隔离性 持久性
    const favor = await Favor.findOne({
      where: {
        art_id,
        type,
        uid
      }
    })

    if(favor) {
      throw new global.errs.LikeError()
    }
    // 事务 一定要加return
    return sequelize.transaction(async t => {
      await Favor.create({
        art_id,
        type,
        uid
      }, {transaction: t})
      const art = await Art.getData(art_id, type)
      await art.increment('fav_nums', {
        by: 1,
        transaction: t
      })
    })
  }
  // 取消喜欢
  static async disLike(art_id, type, uid) {
    const favor = await Favor.findOne({
      where: {
        art_id, type, uid
      }
    })

    // 如果没拿到数据，用户则没点赞过
    if (!favor) {
      throw new global.errs.DislikeError()
    }
    console.log(Art, '1221')
    return sequelize.transaction(async t => {

      //  destroy 删除数据 ； force 为false是软删除，不会讲数据从表删除，只会插入一个删除的时间戳
      await favor.destroy({ force: true, transaction: t })
      const art = await Art.getData(art_id, type, false)  // 获取期刊信息
      // 指明操作字段， by 指明减少多少
      await art.decrement('fav_nums', {by: 1, transaction: t})  // 更新数据
    })
  }
   // 获取用户是否点击喜欢
  static async userLikeIt(art_id, type, uid) {
    const favor = await Favor.findOne({
      where: {
        uid,
        art_id,
        type,
      }
    })
    return favor ? true : false
  }

  
}
Favor.init({
  uid: Sequelize.INTEGER,
  art_id: Sequelize.INTEGER,
  type: Sequelize.INTEGER
}, {
  sequelize,
  tableName: 'favor'
}) 

module.exports = {
  Favor
}